from django.db.models.signals import pre_save, post_delete
from django.dispatch import receiver
from django.utils.crypto import get_random_string
from django.conf import settings

from .models import Post, Category


@receiver(pre_save, sender=Post)  # pre_save.connect(create_slug, sender=Post)
def create_post_slug(sender, instance, *args, **kwargs):
    """在文章创建之前，自动生成短标题(slug)"""
    if not instance.slug:
        instance.slug = get_random_string(settings.SLUG_SIZE)


@receiver(pre_save, sender=Category)
def create_category_slug(sender, instance, *args, **kwargs):
    """在栏目创建之前，自动生成短标题(slug)"""
    if not instance.slug:
        instance.slug = get_random_string(settings.SLUG_SIZE)
